package com.foreveross.timer;

import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.application.IRollbackTaskFromMQApplication;
import com.foreveross.application.ITaskToMQApplication;
import com.foreveross.taskservice.common.CacheDataSpace;
import com.foreveross.taskservice.common.model.AbstractTaskModel;
import com.foreveross.taskservice.common.mq.destination.DestinationFactory;
import com.foreveross.util.QueueUtil;
import com.foreveross.util.SpringHelper;
import com.foreveross.util.cfg.defaults.DefaultPropertiesLoader;


public class MqPensateTimer {
	private static final Logger LOG = LoggerFactory.getLogger(MqPensateTimer.class);
	
	int MAXSIZE = 100;//每次获取回滚消息数量
	
	IRollbackTaskFromMQApplication reciveApplication;
	ITaskToMQApplication sendApplication;

	public MqPensateTimer(){
		 reciveApplication = (IRollbackTaskFromMQApplication)SpringHelper.getBean("rollbackTaskFromMQApplicationImpl");
		 sendApplication = (ITaskToMQApplication)SpringHelper.getBean("taskToMQApplicationImpl");
		 k();
	}
	public void k() {
		String delay=DefaultPropertiesLoader.getMqpensateTimerDelay();
		if(delay == null || "".equals(delay)){
			delay="0";//默认0毫秒，即程序启动就执行
		}
		String period = DefaultPropertiesLoader.getMqpensateTimerPeriod();
		if(period == null || "".equals(period)){
			LOG.error("定时器未配置任务间隔时间");
			return ;
		}
		TimerTask task = new TimerTask() {
			public void run() {
				job();
			}
		};
		task.run();
		
		Timer timer = new Timer();
		// 第一参数 从第几秒开始  第二参数 表示 每隔多少秒执行一个任务
		timer.schedule(task, Long.parseLong(delay),Long.parseLong(period));
	}
	
	public void job() {
		try {
			//获取回滚消息
			List<AbstractTaskModel> models =reciveApplication.rolls(DestinationFactory.getInstance().getRollbackDestination(CacheDataSpace.AirFreightSpace()),MAXSIZE);
			System.out.println(models);

			//推送回滚消息
			sendApplication.sendTasks(models);
			
			} catch (Exception e) {
				e.printStackTrace();
			}
	}
	
}
